from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask_login import login_required
from models import db, Communication, HierarchyConfig, RequirementPool
from datetime import datetime
import re
from utils.export_utils import export_to_excel


communication_bp = Blueprint('communication', __name__, url_prefix='/communication')

@communication_bp.route('/export', methods=['GET'])
def export_communications():
    # 获取所有沟通纪要
    communications = Communication.query.all()
    
    # 转换为字典列表
    comm_list = []
    for comm in communications:
        comm_dict = {
            "comm_id": comm.comm_id,
            "meeting_time": comm.meeting_time.strftime('%Y-%m-%d %H:%M'),
            "location": comm.location,
            "department": comm.department,
            "recorder": comm.recorder,
            "proposer": comm.proposer,
            "method": comm.method,
            "content": comm.content,
            "notes": comm.notes,
            "related_req_id": comm.related_req_id,
            "l3_value_stream": comm.l3_value_stream,
            "action_items": comm.action_items.replace('\n', '; ') if comm.action_items else "",
            "status": comm.status
        }
        comm_list.append(comm_dict)
    
    # 列名映射（可选，用于更友好的列名）
    columns_mapping = {
        "comm_id": "纪要ID",
        "meeting_time": "时间",
        "location": "地点",
        "department": "部门",
        "recorder": "记录人",
        "proposer": "提出人",
        "method": "方式",
        "content": "沟通纪要",
        "notes": "备注信息",
        "related_req_id": "关联需求ID",
        "l3_value_stream": "L3价值流",
        "action_items": "行动项",
        "status": "状态"
    }
    
    return export_to_excel(comm_list, "沟通纪要", columns_mapping)

def generate_comm_id():
    """生成沟通纪要ID：MTG-YYYYMMDD-001"""
    today_str = datetime.now().strftime('%Y%m%d')
    last_comm = Communication.query.filter(
        Communication.comm_id.like(f'MTG-{today_str}-%')
    ).order_by(Communication.comm_id.desc()).first()
    
    if last_comm:
        last_num = int(last_comm.comm_id.split('-')[-1])
        new_num = last_num + 1
    else:
        new_num = 1
    return f'MTG-{today_str}-{new_num:03d}'

@communication_bp.route('/')
def index():
    communications = Communication.query.order_by(Communication.meeting_time.desc()).all()
    return render_template('communication/index.html', communications=communications)

@communication_bp.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        # 生成唯一ID
        comm_id = generate_comm_id()
        
        # 创建新沟通纪要
        new_comm = Communication(
            comm_id=comm_id,
            meeting_time=datetime.strptime(request.form['meeting_time'], '%Y-%m-%dT%H:%M'),
            location=request.form['location'],
            department=request.form['department'],
            recorder=request.form['recorder'],
            proposer=request.form['proposer'],
            method=request.form['method'],
            content=request.form['content'],
            notes=request.form.get('notes', ''),
            related_req_id=request.form.get('related_req_id', None),
            l3_value_stream=request.form.get('l3_value_stream', None),
            action_items=request.form.get('action_items', '')
        )
        
        db.session.add(new_comm)
        db.session.commit()
        flash('沟通纪要创建成功!', 'success')
        return redirect(url_for('communication.index'))


    # 获取现有需求用于关联
    requirements = RequirementPool.query.all()
    # 获取L3层级节点用于价值流推荐
    l3_nodes = HierarchyConfig.query.filter_by(level='L3').all()
    return render_template('communication/create.html', 
                          requirements=requirements,
                          l3_nodes=l3_nodes)

@communication_bp.route('/detail/<string:comm_id>', methods=['GET'])
def detail(comm_id):
    # 占位路由，后续可替换为实际实现
    return render_template('communication/detail.html', comm_id=comm_id)

@communication_bp.route('/edit/<string:comm_id>', methods=['GET', 'POST'])
def edit(comm_id):
    comm = Communication.query.get_or_404(comm_id)
    
    if request.method == 'POST':
        comm.meeting_time = datetime.strptime(request.form['meeting_time'], '%Y-%m-%dT%H:%M')
        comm.location = request.form['location']
        comm.department = request.form['department']
        comm.recorder = request.form['recorder']
        comm.proposer = request.form['proposer']
        comm.method = request.form['method']
        comm.content = request.form['content']
        comm.notes = request.form.get('notes', '')
        comm.related_req_id = request.form.get('related_req_id', None)
        comm.l3_value_stream = request.form.get('l3_value_stream', None)
        comm.action_items = request.form.get('action_items', '')
        
        db.session.commit()
        flash('沟通纪要更新成功!', 'success')
        return redirect(url_for('communication.index'))
    
    requirements = RequirementPool.query.all()
    l3_nodes = HierarchyConfig.query.filter_by(level='L3').all()
    return render_template('communication/edit.html', 
                          comm=comm,
                          requirements=requirements,
                          l3_nodes=l3_nodes)

@communication_bp.route('/delete/<string:comm_id>', methods=['POST'])
def delete(comm_id):
    comm = Communication.query.get_or_404(comm_id)
    db.session.delete(comm)
    db.session.commit()
    flash('沟通纪要已删除!', 'success')
    return redirect(url_for('communication.index'))